package com.action.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.struts2.ServletActionContext;

public class UploadFileAction extends BaseAction{
	
	private static final long serialVersionUID = 572146812454l;
	private static final int BUFFER_SIZE = 10 * 1024;

	private File myFile;
	private String fileName;
	private String filena;
	private File msUploadFile;

	public void uploadFileByStruts2(){
		String filePath= ServletActionContext.getServletContext().getRealPath("/upfile");
		File file1 = new File(filePath);
		
		// 判断文件或目录是否存在。
		if (!file1.exists()) {
			file1.mkdir();// 目录不存在的情况下，创建目录。
		}
		
		File file = new File(filePath+"/"+fileName);
		
		copy(msUploadFile, file);
		
		
//		如果重命名文件名, 请启用此几行代码
//		String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
//		File file = new File(filePath+"/"+filena+ "." + fileExt);
//		copy(msUploadFile, file);
//		PagesUtil.outDataToPage("ok");
	}
	private static void copy(File src, File dst) {
		try {
			InputStream in = null;
			OutputStream out = null;
			try {
				in = new BufferedInputStream(new FileInputStream(src),
						BUFFER_SIZE);
				out = new BufferedOutputStream(new FileOutputStream(dst),
						BUFFER_SIZE);
				byte[] buffer = new byte[BUFFER_SIZE];
				int readLen = 0;
				
				while ((readLen = in.read(buffer)) != -1) {
					out.write(buffer, 0, readLen);
				}
			} finally {
				if (null != in) {
					in.close();
				}
				if (null != out) {
					out.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String getFilena() {
		return filena;
	}

	public void setFilena(String filena) {
		this.filena = filena;
	}

	public File getMsUploadFile() {
		return msUploadFile;
	}

	public void setMsUploadFile(File msUploadFile) {
		this.msUploadFile = msUploadFile;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	public void setMyFileFileName(String fileName) {
		this.fileName = fileName;
	}

	public void setMyFile(File myFile) {
		this.myFile = myFile;
	}

	public String getFileName() {
		return fileName;
	}
	
	public File getMyFile() {
		return myFile;
	}

}
